package http.zjitc.net.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private Button btn_download;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        btn_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getRequest();
            }
        });
    }

    private void getRequest() {
        //1.创建request对象，设置url地址，设置请求方法
        Request.Builder requestBuilder=new Request.Builder().url("http://vux-cdn.sunteorum.com/voiux/gallery/da0279d23c45a2c6d160632f21797747.jpg");
        requestBuilder.method("GET",null);
        Request request=requestBuilder.build();
        //2.创建okHttpCilent对象
        final OkHttpClient okHttpClient=new OkHttpClient();
        //3.创建call对象，参数是Request请求对象
        Call call=okHttpClient.newCall(request);
        //4.请求加入队列，重写回调方法
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[] bytes=response.body().bytes();

                //把bytes字节组转成图片
                final Bitmap bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }

    private void init() {
        btn_download=findViewById(R.id.btn_download);
        imageView=findViewById(R.id.iv);
    }
}
